package com.qingzhou.common.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.qingzhou.common.constants.HttpConstant;
import com.qingzhou.common.web.api.ApiCodes;
import org.noear.solon.Utils;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.UploadedFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 文件 工具类
 * @author xm
 */
public class FileUtil {

    /**
     * 上传
     * @param file
     * @param maxSize
     * @param fileType
     * @return
     */
    public static String upload(UploadedFile file, long maxSize, List<String> fileType, String savePath, String requestPrefix) {
        try {
            checkFile(file, maxSize, fileType);
            String fileName = StrUtil.isEmpty(file.getExtension()) ? Utils.guid() : Utils.guid() + "." + file.getExtension();
            String key = File.separator + DateUtil.today() + File.separator + fileName;
            File saveFile = new File(savePath + key);
            if (!saveFile.exists()) {
                if (!saveFile.getParentFile().exists()) {
                    saveFile.getParentFile().mkdirs();
                }
            }
            file.transferTo(saveFile);
            return requestPrefix + key;
        } catch (Exception e) {
            throw ApiCodes.CODE_400(e);
        }
    }

    /**
     * 下载
     * @param byteArrayOutputStream
     * @return
     */
    public static void download(ByteArrayOutputStream byteArrayOutputStream) {
        Context ctx = ContextUtil.getContext();
        ctx.contentType(HttpConstant.CONTENT_TYPE_FORM);
        try {
            byteArrayOutputStream.writeTo(ctx.outputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                byteArrayOutputStream.close();
            } catch (IOException e) {
            }
        }
    }

    /**
     * 校验文件
     * @param file
     * @param maxSize
     * @param fileType
     */
    private static void checkFile(UploadedFile file, long maxSize, List<String> fileType) {
        try {
            if(file == null || file.isEmpty()) {
                throw ApiCodes.CODE_400("文件为空");
            }
            if(maxSize != -1 && file.getContentSize() > maxSize * 1024 * 1024) {
                throw ApiCodes.CODE_400("请上传 " + maxSize + "M 以内的文件");
            }
            if(!fileType.contains(file.getExtension())) {
                throw ApiCodes.CODE_400("不支持此类文件上传");
            }
        } catch (Exception e) {
            throw ApiCodes.CODE_400(e);
        }
    }

}
